package com.yanqu.road.server.gameplayer.module.player;

import com.yanqu.road.entity.config.player.HouseCreditInfo;
import com.yanqu.road.entity.config.skill.SkillInfo;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.log.LogHouseBankBarDispatch;
import com.yanqu.road.entity.log.LogHouseBankCreditUpgrade;
import com.yanqu.road.entity.player.UserHouseBar;
import com.yanqu.road.entity.player.UserHouseBarDispatch;
import com.yanqu.road.logic.bussiness.player.UserHouseBussiness;
import com.yanqu.road.logic.pb.HousePb;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.entity.config.player.HouseInfo;
import com.yanqu.road.entity.player.UserHouse;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.pb.house.HouseProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.skin.SkinModule;
import com.yanqu.road.server.manger.DataAnalyticsMgr;
import com.yanqu.road.server.manger.config.HouseMgr;
import com.yanqu.road.server.manger.config.SkillMgr;
import com.yanqu.road.server.manger.config.SkinMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.rank.RankMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class HouseModule extends GeneralModule {

    private UserHouse userHouse;

    private Map<Integer, UserHouseBar> userHouseBarMap;

    /**
     * 记录上一次的派遣门客
     */
    private UserHouseBarDispatch userHouseBarDispatch;

    public HouseModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean loadData() {
        userHouse = UserHouseBussiness.getUserHouse(player.getUserId());
        userHouseBarMap = UserHouseBussiness.getUserHouseBarMap(player.getUserId());
        userHouseBarDispatch = UserHouseBussiness.getUserHouseBarDispatch(player.getUserId());
        initUserHouse();
        initSkillList();
        initUserHouseBarDispatch();
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {
        if(null != userHouse){
            if(userHouse.isInsertOption()){
                UserHouseBussiness.addUserHouse(userHouse);
            }else if(userHouse.isUpdateOption()){
                UserHouseBussiness.updateUserHouse(userHouse);
            }
        }
        for (UserHouseBar userHouseBar : userHouseBarMap.values()) {
            if (userHouseBar.isInsertOption()) {
                UserHouseBussiness.addUserHouseBar(userHouseBar);
            }else if (userHouseBar.isUpdateOption()) {
                UserHouseBussiness.updateUserHouseBar(userHouseBar);
            }
        }
        if (null != userHouseBarDispatch) {
            if (userHouseBarDispatch.isInsertOption()) {
                UserHouseBussiness.addUserHouseBarDispatch(userHouseBarDispatch);
            } else if (userHouseBarDispatch.isUpdateOption()) {
                UserHouseBussiness.updateUserHouseBarDispatch(userHouseBarDispatch);
            }
        }
        return true;
    }

    @Override
    public void loginSendMsg() {
        syncUserHouse();
    }

    @Override
    public void afterLogin() {
        syncUserHouseBank();
    }

    private void initUserHouse(){
        if(null == userHouse){
            UserHouse house = new UserHouse();
            house.setUserId(player.getUserId());
            house.setLastClickTime(System.currentTimeMillis());
            house.setTotalClickTimes(0L);
            house.setInsertOption();
            userHouse = house;
            //成就、任务
            player.notifyListener(eGamePlayerEventType.HouseLevel.getValue(), player.getUserInfo().getHouseLv());
        }
    }

    private void initUserHouseBarDispatch() {
        if (userHouseBarDispatch == null) {
            UserHouseBarDispatch houseBarDispatch = new UserHouseBarDispatch();
            houseBarDispatch.setUserId(player.getUserId());
            List<Integer> dispatchPatronsList = new ArrayList<>();
            for (UserHouseBar userHouseBar : userHouseBarMap.values()) {
                if (userHouseBar == null) {
                    continue;
                }
                if (userHouseBar.getPatronsId() != 0) {
                    dispatchPatronsList.add(userHouseBar.getPatronsId());
                }
            }
            houseBarDispatch.setDispatchPatronsList(dispatchPatronsList);
            houseBarDispatch.setInsertOption();
            userHouseBarDispatch = houseBarDispatch;
        }
    }

    public void syncUserHouse(){
        HouseProto.HouseTempMsg.Builder msg = HousePb.parseHouseTempMsg(player.getUserInfo().getHouseLv(),player.getUserInfo().getBankSkinId());
        if(null != msg){
            player.sendPacket(Protocol.U_HOUSE_SYNC, msg);
        }
    }

    public int changeSkin(int skinId){
        if(!SkinMgr.isBankSkin(skinId) && skinId != 0){
            return GameErrorCode.E_SKIN_NOT_EXIST;
        }
        boolean skinExist = player.getModule(SkinModule.class).isSkinExist(skinId);
        if (!skinExist && skinId != 0) {
            return GameErrorCode.E_ESTATE_WAR_NO_ESTATE_SKIN;
        }
        player.getUserInfo().setBankSkinId(skinId);
        syncUserHouse();
        return 0;
    }




    //钱庄同步
    public void syncUserHouseBank(){
        HouseProto.HouseBarSyncMsg.Builder msg = HouseProto.HouseBarSyncMsg.newBuilder();
        msg.setHouseCreditLevel(player.getUserInfo().getHouseCreditLv());
        msg.setHouseCreditValue(player.getModule(AttributeModule.class).getAttribute(ePlayerAttrType.HouseCreditValue));
        for(UserHouseBar userHouseBar : userHouseBarMap.values()){
            msg.addBarList(HousePb.parseHouseBarInfoTempMsg(userHouseBar));
        }
        for (Integer patronsId : userHouseBarDispatch.getDispatchPatronsList()) {
            msg.addPatronsList(patronsId);
        }
        player.sendPacket(Protocol.U_HOUSE_BAR_SYNC, msg);
    }


    /**
     * 设置派遣门客
     */
    public void setDispatchPatronsList(List<Integer> dispatchPatronsList) {
        userHouseBarDispatch.setDispatchPatronsList(dispatchPatronsList);
    }

    /**
     * 钱庄升级
     */
    public int houseUpgrade(){
        UserInfo userInfo = player.getUserInfo();
        HouseInfo nextHouse = HouseMgr.getHouseInfo(userInfo.getHouseLv() + 1);
        if(null == nextHouse){
            return GameErrorCode.E_HOUSE_LEVEL_MAX;
        }
        HouseInfo houseInfo = HouseMgr.getHouseInfo(userInfo.getHouseLv());
        //消耗
        if(!player.getModule(CurrencyModule.class).removeCurrency(houseInfo.getUpgradeConsume(), eLogMoneyType.System, eLogMoneyType.HouseUpgrade)){
            player.notifyListener(eGamePlayerEventType.RechargeBankSkin.getValue(), 0);
            return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
        }
        //触发钱庄皮肤现金礼包，点了升级就触发，不管成功不成功
        player.notifyListener(eGamePlayerEventType.RechargeBankSkin.getValue(), 0);
        //触发现金礼包
        if(!player.getModule(CurrencyModule.class).currencyIsEnough(nextHouse.getUpgradeConsume())){//不足下次升级触发
            player.notifyListener(eGamePlayerEventType.RechargeHouseUpgrade.getValue(), 0);
        }


        //增加等级
        userInfo.setHouseLv(userInfo.getHouseLv() + 1);
        syncUserHouse();
        onHouseChange();
        //成就、任务
        player.notifyListener(eGamePlayerEventType.HouseLevel.getValue(), userInfo.getHouseLv());

        DataAnalyticsMgr.trackHouseUpgrade(player, userInfo.getHouseLv());
        return 0;
    }

    public void autoClickHouse(long time) {
        HouseInfo houseInfo = HouseMgr.getHouseInfo(player.getUserInfo().getHouseLv());
        BigInteger silver = houseInfo.getClickAddSilver().multiply(BigInteger.valueOf(houseInfo.getAutoClickTimes() * time));
        if (silver.compareTo(BigInteger.ZERO) > 0) {
            player.getModule(CurrencyModule.class).addCurrency(new Property(GameConfig.GAME_MONEY_SILVER, silver),
                    eLogMoneyType.System, eLogMoneyType.AutoClickHouse);
        }
    }

    public int getEarnSpeedAddition(){
        HouseInfo houseInfo = HouseMgr.getHouseInfo(player.getUserInfo().getHouseLv());
        return houseInfo.getEarnSpeedAddition();
    }

    public UserHouse getUserHouse() {
        return userHouse;
    }

    private void onHouseChange(){
        player.getModule(EarnSpeedModule.class).scheduleAddSilver();
    }

    public Map<Integer,UserHouseBar> getUserHouseBarMap(){
        return userHouseBarMap;
    }

    public UserHouseBarDispatch getUserHouseBarDispatch() {
        return userHouseBarDispatch;
    }

    /**
     * 增加钱庄柜台
     * @param pos
     */
    public void addHouseBar(int pos){
        if(userHouseBarMap.containsKey(pos)){
            return;
        }
        UserHouseBar userHouseBar = new UserHouseBar();
        userHouseBar.setUserId(getUserId());
        userHouseBar.setBarPos(pos);
        userHouseBar.setPatronsId(0);
        userHouseBar.setOpenTime(System.currentTimeMillis());
        userHouseBar.setLastRewardTime(0);
        userHouseBar.setSurplusTime(0);
        userHouseBar.setDispatchTime(0);
        userHouseBar.setToadSilver("0");
        userHouseBar.setInsertOption();
        userHouseBarMap.put(userHouseBar.getBarPos(),userHouseBar);
    }


    public void addHouseCredit(long value,eLogMoneyType master,eLogMoneyType son){
        player.getModule(AttributeModule.class).addAttribute(ePlayerAttrType.HouseCreditValue,value);
        player.notifyListener(eGamePlayerEventType.BankCreditValue.getValue(), player.getModule(AttributeModule.class).getAttribute(ePlayerAttrType.HouseCreditValue));
        player.notifyListener(eGamePlayerEventType.BankCreditValueAdd.getValue(), value);
        changeCreditValueRank();
//        syncUserHouseBank();
    }

    public boolean isEnoughHouseCredit(long value, eLogMoneyType master, eLogMoneyType son) {
        if (value <= 0) {
            return false;
        }
        AttributeModule attributeModule = player.getModule(AttributeModule.class);
        return attributeModule.getAttribute(ePlayerAttrType.HouseCreditValue) >= value;
    }

    public void houseCreditUpgrade(){
        player.getUserInfo().setHouseCreditLv(player.getUserInfo().getHouseCreditLv() + 1);
        changeCreditValueRank();
        syncUserHouseBank();
        initSkillList();
        AutoLogMgr.add(new LogHouseBankCreditUpgrade(
                player.getUserId(),
                player.getUserInfo().getEarnSpeed().toString(),
                player.getUserInfo().getTitleId(),
                player.getUserInfo().getVipExp(),
                player.getUserInfo().getHouseCreditLv()
        ));
    }

    private List<Integer> skillList = new ArrayList<>();//钱庄信誉等级技能

    private Map<Integer, Map<Integer, Integer>> identitySkillAdditionMap = new ConcurrentHashMap<>();//钱庄信誉等级技能加成

    //初始技能列表，生效对应等级的技能
    private void initSkillList(){
        skillList = new ArrayList<>();
        HouseCreditInfo houseCreditInfo = HouseMgr.getHouseCreditInfo(player.getUserInfo().getHouseCreditLv());
        if(houseCreditInfo == null){
            return;
        }
        List<Integer> skillListTemp = StringUtils.stringToIntegerList(houseCreditInfo.getSkillsList(),"\\|");
        for(Integer skillId : skillListTemp){
            if(skillId != 0){
                skillList.add(skillId);
            }
        }
        identitySkillAdditionMap = SkillMgr.initHouseSkillAdditionMap(skillList);
    }

    public int getIdentitySkillAddition(int skillType, int param){
        return SkillMgr.getSkillAdditionFromMap(skillType, param, identitySkillAdditionMap);
    }
    /**
     * 获取对应职业的加成值
     * @param occupationType
     * @return
     */
    public int getAddChildValue(int occupationType) {//params的第三个参数只会配0的所有职业生效的，不是0就是配错了
        int addValue = 0;
        for(Integer skillId : skillList){
            SkillInfo skillInfo = SkillMgr.getSkillInfo(skillId);
            if (skillInfo == null) {
                log.error("钱庄 skill is null. skillId : {}", skillId);
                continue;
            }
            if (skillInfo.getType() == eSkillType.AddChildAbility.getValue()) {
                addValue = addValue + SkillMgr.getSkillAddition(skillInfo, 1);
            }
        }
        return addValue;
    }

    /**
     * 榜单变更
     */
    public void changeCreditValueRank() {
        try {
            long value = player.getModule(AttributeModule.class).getAttribute(ePlayerAttrType.HouseCreditValue);
            RankMgr.changeUserRank(eBigRankType.Normal.getValue(), player.getUserId(), BigInteger.valueOf(value), eRankType.CreditValue.getValue(), player.getUserInfo().getHouseCreditLv() + "");
        } catch (Exception ex) {
            log.error(ex);
        }
    }


    //判断多少个坑位坐人了，防止新手引导被刷
    private int dispatchPatronsCount(){
        int count = 0;
        for(UserHouseBar userHouseBar : userHouseBarMap.values()){
            if(userHouseBar.getPatronsId() != 0){
                count++;
            }
        }
        return count;
    }

    public int dispatchPatrons(Map<Integer,Integer> posPatronsMap){
        int num = 0;
        for(Integer pos : posPatronsMap.keySet()){
            UserHouseBar userHouseBar = userHouseBarMap.get(pos);
            if(userHouseBar == null){
                continue;
            }
            num++ ;
            //第一个坑位新手引导给一天收益
            if(dispatchPatronsCount() == 0 && player.getModule(AttributeModule.class).getAttribute(ePlayerAttrType.HouseCreditValue) == 0){
                userHouseBar.setPatronsId(posPatronsMap.get(pos));
                userHouseBar.setDispatchTime(System.currentTimeMillis() - 24 * 60 * 60 * 1000);
            }else{
                userHouseBar.setPatronsId(posPatronsMap.get(pos));
                userHouseBar.setDispatchTime(System.currentTimeMillis());
            }
        }
        // 保存当前的门客派遣
        List<Integer> dispatchPatronsList = new ArrayList<>();
        for (UserHouseBar userHouseBar : userHouseBarMap.values()) {
            if(userHouseBar == null){
                continue;
            }
            if (userHouseBar.getPatronsId() != 0) {
                dispatchPatronsList.add(userHouseBar.getPatronsId());
            }
        }
        setDispatchPatronsList(dispatchPatronsList);
        return num;
    }

    public Map<String,Property> recallPatrons(Map<Integer,Integer> posPatronsMap){
        Map<String,Property> rewardMap = new ConcurrentHashMap<>();
        for(Integer pos : posPatronsMap.keySet()){
            Property reward = new Property();
            UserHouseBar userHouseBar = userHouseBarMap.get(pos);
            if(userHouseBar == null){
                continue;
            }
            int patronsId = userHouseBar.getPatronsId();
            long dispatchTime = userHouseBar.getDispatchTime();
            long produceTime = HouseMgr.getHouseProduceTime(player.getUserInfo().getHouseCreditLv()) * 1000;
            long dispatchTimeAll = getDispatchTimeAll(userHouseBar);
            long rewardTimes = dispatchTimeAll/produceTime;
            long surplusTime = dispatchTimeAll%produceTime;

            userHouseBar.setDispatchTime(0);
            userHouseBar.setPatronsId(0);
            userHouseBar.setSurplusTime(surplusTime);

            if(rewardTimes != 0){
                reward = HouseMgr.getBankProduceReward(player.getUserInfo().getHouseCreditLv(),rewardTimes);
                //金蟾银币撤回了就收到柜台里
                BigInteger totalSilver = new BigInteger(userHouseBar.getToadSilver());
                totalSilver = totalSilver.add(reward.getCountByGoodsId(GameConfig.GAME_MONEY_SILVER));
                userHouseBar.setToadSilver(totalSilver.toString());
                userHouseBar.setLastRewardTime(System.currentTimeMillis());

                player.getModule(PatronsModule.class).addBaiyeExp(patronsId,reward.getCountByGoodsId(GameConfig.PATRONS_BAIYE_EXP_ID).longValue());
                player.getModule(PatronsModule.class).addChousuanExp(patronsId,reward.getCountByGoodsId(GameConfig.PATRONS_CHOUSUAN_EXP_ID).longValue());
                addLuckValue(pos,reward.getCountByGoodsId(GameConfig.GAME_ITEM_HOUSE_BANK_LUCK_ID).longValue());
                player.getModule(CurrencyModule.class).addCurrency(reward,eLogMoneyType.HouseBank,eLogMoneyType.HouseBankPatronsRecall);
                AutoLogMgr.add(new LogHouseBankBarDispatch(
                        player.getUserId(),
                        patronsId,
                        pos,
                        reward.getCountByGoodsId(GameConfig.PATRONS_BAIYE_EXP_ID).longValue(),
                        reward.getCountByGoodsId(GameConfig.GAME_ITEM_CREDIT).longValue(),
                        reward.getCountByGoodsId(GameConfig.PATRONS_CHOUSUAN_EXP_ID).longValue(),
                        reward.getCountByGoodsId(GameConfig.GAME_ITEM_HOUSE_BANK_LUCK_ID).longValue(),
                        new Date(dispatchTime),
                        dispatchTimeAll/1000,
                        surplusTime/1000
                 ));
            }
            rewardMap.put(pos + "-" + patronsId,reward);
        }
        return rewardMap;
    }

    public Map<String,Property> assistantRecallPatrons(){
        Map<String,Property> rewardMap = new ConcurrentHashMap<>();
        for(Integer pos : userHouseBarMap.keySet()){
            Property reward = new Property();
            UserHouseBar userHouseBar = userHouseBarMap.get(pos);
            if(userHouseBar == null){
                continue;
            }
            long dispatchTime = userHouseBar.getDispatchTime();
            long produceTime = HouseMgr.getHouseProduceTime(player.getUserInfo().getHouseCreditLv()) * 1000;
            long dispatchTimeAll = getDispatchTimeAll(userHouseBar);
            int patronsId = userHouseBar.getPatronsId();
            long rewardTimes = dispatchTimeAll/produceTime;

            if(rewardTimes != 0){
                long surplusTime = dispatchTimeAll%produceTime;

                userHouseBar.setDispatchTime(0);
                userHouseBar.setPatronsId(0);
                userHouseBar.setSurplusTime(surplusTime);
                reward = HouseMgr.getBankProduceReward(player.getUserInfo().getHouseCreditLv(),rewardTimes);
                //金蟾银币撤回了就收到柜台里
                BigInteger totalSilver = new BigInteger(userHouseBar.getToadSilver());
                totalSilver = totalSilver.add(reward.getCountByGoodsId(GameConfig.GAME_MONEY_SILVER));
                userHouseBar.setToadSilver(totalSilver.toString());
                userHouseBar.setLastRewardTime(System.currentTimeMillis());

                player.getModule(PatronsModule.class).addBaiyeExp(patronsId,reward.getCountByGoodsId(GameConfig.PATRONS_BAIYE_EXP_ID).longValue());
                player.getModule(PatronsModule.class).addChousuanExp(patronsId,reward.getCountByGoodsId(GameConfig.PATRONS_CHOUSUAN_EXP_ID).longValue());
                addLuckValue(pos,reward.getCountByGoodsId(GameConfig.GAME_ITEM_HOUSE_BANK_LUCK_ID).longValue());
                player.getModule(CurrencyModule.class).addCurrency(reward,eLogMoneyType.HouseBank,eLogMoneyType.HouseBankPatronsRecall);
                AutoLogMgr.add(new LogHouseBankBarDispatch(
                        player.getUserId(),
                        patronsId,
                        pos,
                        reward.getCountByGoodsId(GameConfig.PATRONS_BAIYE_EXP_ID).longValue(),
                        reward.getCountByGoodsId(GameConfig.GAME_ITEM_CREDIT).longValue(),
                        reward.getCountByGoodsId(GameConfig.PATRONS_CHOUSUAN_EXP_ID).longValue(),
                        reward.getCountByGoodsId(GameConfig.GAME_ITEM_HOUSE_BANK_LUCK_ID).longValue(),
                        new Date(dispatchTime),
                        dispatchTimeAll/1000,
                        surplusTime/1000
                ));
                rewardMap.put(pos + "-" + patronsId,reward);
            }
        }
        return rewardMap;
    }

    private Map<Integer, Integer> getCanRecallPatrons() {
        Map<Integer, Integer> map = new HashMap<>();
        for (UserHouseBar bar : userHouseBarMap.values()) {
            int barPos = bar.getBarPos();
            int produceTime = HouseMgr.getHouseProduceTime(player.getUserInfo().getHouseCreditLv());
        }
        return map;
    }

    //返回每个位置的奖励
    public Map<String,Property> getBarReward(int pos){
        long nowTime = System.currentTimeMillis();
        Map<String,Property> propertyMap = new ConcurrentHashMap<>();
        Map<Integer,UserHouseBar> tempMap = userHouseBarMap;
        if(pos != 0){
            UserHouseBar userHouseBar = userHouseBarMap.get(pos);
            if(userHouseBar == null){
                return propertyMap;
            }
            if(nowTime - userHouseBar.getDispatchTime() + userHouseBar.getSurplusTime() < HouseMgr.getHouseProduceTime(player.getUserInfo().getHouseCreditLv()) * 1000){
                userHouseBar.setSurplusTime(nowTime - userHouseBar.getDispatchTime() + userHouseBar.getSurplusTime());
                return propertyMap;
            }
            tempMap.put(userHouseBar.getBarPos(),userHouseBar);
        }

        for(UserHouseBar userHouseBar : userHouseBarMap.values()){
            int creditLv = player.getUserInfo().getHouseCreditLv();
            long dispatchTime = getDispatchTimeAll(userHouseBar);
            long rewardTimes = dispatchTime/(HouseMgr.getHouseProduceTime(creditLv) * 1000);
            long surplusTime = dispatchTime%(HouseMgr.getHouseProduceTime(creditLv) * 1000);
            userHouseBar.setDispatchTime(nowTime);
            userHouseBar.setSurplusTime(surplusTime);
            if(rewardTimes != 0){
                Property reward = HouseMgr.getBankProduceReward(creditLv,rewardTimes);
                BigInteger totalSilver = new BigInteger(userHouseBar.getToadSilver());
                totalSilver = totalSilver.add(reward.getCountByGoodsId(GameConfig.GAME_MONEY_SILVER));
                userHouseBar.setToadSilver(totalSilver.toString());
                userHouseBar.setLastRewardTime(nowTime);

                propertyMap.put(userHouseBar.getBarPos() + "-" + userHouseBar.getPatronsId(),reward);
                player.getModule(PatronsModule.class).addBaiyeExp(userHouseBar.getPatronsId(),reward.getCountByGoodsId(GameConfig.PATRONS_BAIYE_EXP_ID).longValue());
                long chouSuanExp = reward.getCountByGoodsId(GameConfig.PATRONS_CHOUSUAN_EXP_ID).longValue();
                //酒坊提供的筹算加成；
//                int chouSuanExpAdditionValue = player.getModule(WineryModule.class).getChouSuanExpAdditionValue();
//                chouSuanExp  = chouSuanExp + chouSuanExpAdditionValue;
                player.getModule(PatronsModule.class).addChousuanExp(userHouseBar.getPatronsId(), chouSuanExp);
                addLuckValue(pos,reward.getCountByGoodsId(GameConfig.GAME_ITEM_HOUSE_BANK_LUCK_ID).longValue());
                player.getModule(CurrencyModule.class).addCurrency(reward,eLogMoneyType.HouseBank,eLogMoneyType.HouseBankPatronsReward);
            }
        }
        return propertyMap;
    }

    //增加荣誉值
    private void addLuckValue(int pos,long value){
        long addValue = value;
        if(getTotalLuckValue() >= HouseMgr.getLuckSilverMaxValue()){
            return;
        }else if(getTotalLuckValue() + value >= HouseMgr.getLuckSilverMaxValue()){
            addValue = HouseMgr.getLuckSilverMaxValue() - getTotalLuckValue();
        }
        BigInteger old = new BigInteger(userHouseBarMap.get(pos).getToadSilver());
        userHouseBarMap.get(pos).setToadSilver(old.add(BigInteger.valueOf(addValue)).toString());
    }

    //获取门客派遣的可结算时间
    private long getDispatchTimeAll(UserHouseBar userHouseBar){
        if(userHouseBar.getPatronsId() == 0)return 0;
        long nowTime = System.currentTimeMillis();
        long stayTime;
        //大于最大上限了，直接用最大上限
        if(nowTime - userHouseBar.getDispatchTime() > HouseMgr.getHouseInfo(player.getUserInfo().getHouseLv()).getBankBarTime() * 1000){
            stayTime = HouseMgr.getHouseInfo(player.getUserInfo().getHouseLv()).getBankBarTime() * 1000;
        }else{
            stayTime = nowTime - userHouseBar.getDispatchTime();
        }

        return stayTime + userHouseBar.getSurplusTime();
    }


    //获取金蟾银两奖励
    public long getToadReward(){
        BigInteger totalSilver = BigInteger.ZERO;
        for(UserHouseBar userHouseBar : userHouseBarMap.values()){
            BigInteger silver = new BigInteger(userHouseBar.getToadSilver());
            totalSilver = totalSilver.add(silver);
            userHouseBar.setToadSilver("0");
        }

        return totalSilver.longValue();
    }

    public void initHouseBar(){
        if(player.getUserInfo().getHouseCreditLv() == 0){
            player.getUserInfo().setHouseCreditLv(1);
        }
        player.getModule(PatronsModule.class).syncPatronsDataAll(false);
        /*for(int pos=1;;pos++){
            int cost = HouseMgr.getHouseBarCost(pos);
            if(cost == 0){
                addHouseBar(pos);
            }else{
                break;
            }
        }*/
    }

    //获取总的财运值
    public int getTotalLuckValue(){
        int ret = 0;
        for(UserHouseBar userHouseBar : userHouseBarMap.values()){
            BigInteger temp = new BigInteger(userHouseBar.getToadSilver());
            ret += temp.intValue();
        }
        return ret;
    }

    public int luckSilverGet(){
        int useValue = HouseMgr.getLuckSilverUseValue();
        for(UserHouseBar userHouseBar : userHouseBarMap.values()){
            int barValue = Integer.valueOf(userHouseBar.getToadSilver());
            if(barValue >= useValue){
                userHouseBar.setToadSilver(String.valueOf(barValue - useValue));
                break;
            }else{
                useValue = useValue - barValue;
                userHouseBar.setToadSilver("0");
            }
        }
        return HouseMgr.getRandomLuckSilver();
    }

    public Property recoveryRecallPatrons(int day, int discount) {

        Property totalReward = new Property();
        //所有柜台同一奖励时间
        if (player.getUserInfo().getHouseCreditLv() < 1) {
            return totalReward;
        }
        //收益单位时间
        long produceTime = HouseMgr.getHouseProduceTime(player.getUserInfo().getHouseCreditLv()) * 1000;
        //收益最大时间
        long maxTime = HouseMgr.getHouseInfo(player.getUserInfo().getHouseLv()).getBankBarTime() * 1000;
        //下线后一天0点时间
        long lastRecodeZeroTime = DateHelper.getTodayZeroTimeStamp() - day * DateHelper.DAY_MILLIONS;
        //一天最多收货时间
        long oneDayMaxTime = maxTime > DateHelper.DAY_MILLIONS ? DateHelper.DAY_MILLIONS:maxTime;

        for (Map.Entry<Integer, UserHouseBar> entry : userHouseBarMap.entrySet()) {
            Property reward = new Property();
            if (entry.getValue() == null){
                continue;
            }
            UserHouseBar userHouseBar = entry.getValue();
            long difference = 0;
            //吧台本来就没派遣门客 直接扣满
            if (userHouseBar.getPatronsId() == 0){
                difference = maxTime;

            } else {  //吧台派遣了门客
                //派遣时间加上最大时间=收集满时间 减去下线后一天0点的时间 检测是否下线后一天0点还没有恢复满
                difference = userHouseBar.getDispatchTime() + maxTime - lastRecodeZeroTime;
            }

            long rewardTimes = 0;

            //离线时已满 全量找回 全部折损
            if (difference < 0){
                rewardTimes = oneDayMaxTime * day * discount / produceTime   / 1000;
            } else {        //离线时未满 找回增量
                rewardTimes = (oneDayMaxTime * day - difference) * discount / produceTime /1000;
            }

            if (rewardTimes > 0) {
                reward = HouseMgr.getBankProduceReward(player.getUserInfo().getHouseCreditLv(), rewardTimes);
                //不找这俩
                reward.removeProperty(GameConfig.PATRONS_BAIYE_EXP_ID);
                reward.removeProperty(GameConfig.PATRONS_CHOUSUAN_EXP_ID);

                BigInteger totalSilver = new BigInteger(userHouseBar.getToadSilver());
                totalSilver = totalSilver.add(reward.getCountByGoodsId(GameConfig.GAME_MONEY_SILVER));
                userHouseBar.setToadSilver(totalSilver.toString());

                addLuckValue(entry.getKey(), reward.getCountByGoodsId(GameConfig.GAME_ITEM_HOUSE_BANK_LUCK_ID).longValue());
                player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.RecoveryReward, eLogMoneyType.RecoveryHouseReward);
                AutoLogMgr.add(new LogHouseBankBarDispatch(
                        player.getUserId(),
                        0,
                        entry.getKey(),
                        0,
                        reward.getCountByGoodsId(GameConfig.GAME_ITEM_CREDIT).longValue(),
                        0,
                        reward.getCountByGoodsId(GameConfig.GAME_ITEM_HOUSE_BANK_LUCK_ID).longValue(),
                        new Date(),
                        0,
                        0
                ));
                totalReward.addProperty(reward);
            }
        }
        return totalReward;
    }
}
